package com.example.demo.grbkxt.servlet;

import com.example.demo.grbkxt.mapper.BlogMapper;
import com.example.demo.grbkxt.mapper.CommentMapper;
import com.example.demo.grbkxt.model.Blog;
import com.example.demo.grbkxt.model.Comment;
import com.example.demo.grbkxt.model.User;
import com.example.demo.grbkxt.util.MyBatisUtil;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.util.UUID;

@WebServlet("/comment/*")
public class CommentServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String action = request.getPathInfo();

        if ("/add".equals(action)) {
            addComment(request, response);
        } else if ("/delete".equals(action)) {
            deleteComment(request, response);
        }
    }

    private void addComment(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }

        String blogId = request.getParameter("blogId");
        String content = request.getParameter("content");

        System.out.println("Adding comment - Blog ID: " + blogId + ", User ID: " + user.getId()); // 调试日志

        try (SqlSession session = MyBatisUtil.openSession()) {
            BlogMapper blogMapper = session.getMapper(BlogMapper.class);
            Blog blog = blogMapper.getBlogById(blogId);

            if (blog == null) {
                System.out.println("Blog not found with ID: " + blogId); // 调试日志
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "博客不存在");
                return;
            }

            CommentMapper mapper = session.getMapper(CommentMapper.class);
            Comment comment = new Comment();
            comment.setId(UUID.randomUUID().toString());
            comment.setBlogId(blogId);
            comment.setUserId(user.getId());
            comment.setContent(content);

            mapper.addComment(comment);
            session.commit();

            System.out.println("Comment added successfully"); // 调试日志
            response.sendRedirect(request.getContextPath() + "/blog/view?id=" + blogId);
        } catch (Exception e) {
            System.err.println("Error adding comment: " + e.getMessage()); // 调试日志
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "添加评论失败");
        }
    }

    private void deleteComment(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "请先登录");
            return;
        }

        String commentId = request.getParameter("id");

        try (SqlSession session = MyBatisUtil.openSession()) {
            CommentMapper mapper = session.getMapper(CommentMapper.class);

            // 尝试删除评论，只有当用户是评论作者或管理员时才能成功
            int result = mapper.deleteComment(commentId, user.getId());

            if (result > 0) {
                session.commit();
                response.setStatus(200);
            } else {
                response.sendError(HttpServletResponse.SC_FORBIDDEN, "没有权限删除此评论");
            }
        }
    }
}
